import { Request, Response } from 'express';
import { spawn } from 'child_process';

export const handleQuestion = async (req: Request, res: Response) => {
  try {
    const { question } = req.body;

    if (!question) {
      return res.status(400).json({
        success: false,
        message: '问题不能为空'
      });
    }

    // 调用Python脚本处理问题
    const pythonProcess = spawn('python', [
      'scripts/qa.py',
      question
    ]);

    let answer = '';
    let error = '';

    pythonProcess.stdout.on('data', (data) => {
      answer += data.toString();
    });

    pythonProcess.stderr.on('data', (data) => {
      error += data.toString();
    });

    pythonProcess.on('close', (code) => {
      if (code !== 0) {
        return res.status(500).json({
          success: false,
          message: `处理问题失败: ${error}`
        });
      }

      return res.json({
        success: true,
        answer: answer.trim()
      });
    });

  } catch (error) {
    console.error('处理问题失败:', error);
    res.status(500).json({
      success: false,
      message: error instanceof Error ? error.message : '处理问题失败'
    });
  }
};
